




const usersList = document.getElementById('usersList');
const tokenModal = document.getElementById('tokenModal');
const tokenForm = document.getElementById('tokenForm');
const tokenUserId = document.getElementById('tokenUserId');
const tokenUsername = document.getElementById('tokenUsername');
const xunfeiLimit = document.getElementById('xunfeiLimit');
const qwenLimit = document.getElementById('qwenLimit');


let allUsers = [];


document.addEventListener('DOMContentLoaded', () => {
    console.log('🔐 管理员面板加载完成');
    loadUsers();


    tokenForm.addEventListener('submit', handleTokenSubmit);
});




async function loadUsers() {
    try {
        const response = await fetch('/api/admin/users', {
            credentials: 'include'
        });

        const result = await response.json();

        if (result.success) {
            allUsers = result.users;
            displayUsers(allUsers);
        } else {
            throw new Error(result.error || '加载失败');
        }
    } catch (error) {
        console.error('❌ 加载用户列表失败:', error);
        usersList.innerHTML = `
            <p class="placeholder">加载失败: ${error.message}</p>
        `;
    }
}




function displayUsers(users) {
    if (users.length === 0) {
        usersList.innerHTML = '<p class="placeholder">暂无用户</p>';
        return;
    }

    const tableHTML = `
        <table class="user-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>用户名</th>
                    <th>邮箱</th>
                    <th>角色</th>
                    <th>状态</th>
                    <th>讯飞API</th>
                    <th>通义千问</th>
                    <th>注册时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                ${users.map(user => createUserRow(user)).join('')}
            </tbody>
        </table>
    `;

    usersList.innerHTML = tableHTML;
}




function createUserRow(user) {
    const xunfeiPercent = (user.xunfei_tokens_used / user.xunfei_token_limit * 100).toFixed(1);
    const qwenPercent = (user.qwen_tokens_used / user.qwen_token_limit * 100).toFixed(1);

    const xunfeiClass = xunfeiPercent > 90 ? 'danger' : (xunfeiPercent > 70 ? 'warning' : '');
    const qwenClass = qwenPercent > 90 ? 'danger' : (qwenPercent > 70 ? 'warning' : '');

    const isAdmin = user.role === 'admin';

    return `
        <tr>
            <td>${user.id}</td>
            <td><strong>${escapeHtml(user.username)}</strong></td>
            <td>${escapeHtml(user.email)}</td>
            <td>
                <span class="badge badge-${user.role}">
                    ${user.role === 'admin' ? '👑 管理员' : '👤 用户'}
                </span>
            </td>
            <td>
                <span class="badge badge-${user.is_active ? 'active' : 'frozen'}">
                    ${user.is_active ? '✓ 正常' : '❄️ 冻结'}
                </span>
            </td>
            <td>
                <div class="token-info">${user.xunfei_tokens_used} / ${user.xunfei_token_limit}</div>
                <div class="progress-bar">
                    <div class="progress-fill ${xunfeiClass}" style="width: ${Math.min(xunfeiPercent, 100)}%"></div>
                </div>
            </td>
            <td>
                <div class="token-info">${user.qwen_tokens_used} / ${user.qwen_token_limit}</div>
                <div class="progress-bar">
                    <div class="progress-fill ${qwenClass}" style="width: ${Math.min(qwenPercent, 100)}%"></div>
                </div>
            </td>
            <td>${formatDate(user.created_at)}</td>
            <td>
                <button class="action-btn btn-set" onclick="openTokenModal(${user.id}, '${escapeHtml(user.username)}', ${user.xunfei_token_limit}, ${user.qwen_token_limit})">
                    ⚙️ 设置
                </button>
                <button class="action-btn btn-reset" onclick="resetTokens(${user.id}, '${escapeHtml(user.username)}')">
                    🔄 重置
                </button>
                ${!isAdmin ? (
                    user.is_active ?
                        `<button class="action-btn btn-freeze" onclick="freezeUser(${user.id}, '${escapeHtml(user.username)}')">❄️ 冻结</button>` :
                        `<button class="action-btn btn-unfreeze" onclick="unfreezeUser(${user.id}, '${escapeHtml(user.username)}')">🔥 解冻</button>`
                ) : '<span style="color: #999; font-size: 12px;">🔒 受保护</span>'}
                ${!isAdmin ?
                    `<button class="action-btn btn-delete" onclick="deleteUser(${user.id}, '${escapeHtml(user.username)}')">🗑️ 删除</button>` :
                    ''
                }
            </td>
        </tr>
    `;
}




function openTokenModal(userId, username, xunfeiLimit, qwenLimit) {
    tokenUserId.value = userId;
    tokenUsername.textContent = `用户: ${username}`;
    xunfeiLimit.value = xunfeiLimit;
    qwenLimit.value = qwenLimit;

    tokenModal.classList.add('show');
}




function closeTokenModal() {
    tokenModal.classList.remove('show');
    tokenForm.reset();
}




async function handleTokenSubmit(e) {
    e.preventDefault();

    const userId = tokenUserId.value;
    const xunfei = parseInt(xunfeiLimit.value);
    const qwen = parseInt(qwenLimit.value);

    try {
        const response = await fetch(`/api/admin/users/${userId}/tokens`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                xunfei_limit: xunfei,
                qwen_limit: qwen
            }),
            credentials: 'include'
        });

        const result = await response.json();

        if (result.success) {
            alert('✅ Token限制已更新');
            closeTokenModal();
            loadUsers();
        } else {
            throw new Error(result.error || '更新失败');
        }
    } catch (error) {
        console.error('❌ 更新Token失败:', error);
        alert('更新失败: ' + error.message);
    }
}




async function resetTokens(userId, username) {
    if (!confirm(`确定要重置 ${username} 的Token使用量吗？`)) {
        return;
    }

    try {
        const response = await fetch(`/api/admin/users/${userId}/reset-tokens`, {
            method: 'POST',
            credentials: 'include'
        });

        const result = await response.json();

        if (result.success) {
            alert('✅ Token使用量已重置');
            loadUsers();
        } else {
            throw new Error(result.error || '重置失败');
        }
    } catch (error) {
        console.error('❌ 重置Token失败:', error);
        alert('重置失败: ' + error.message);
    }
}




async function freezeUser(userId, username) {
    if (!confirm(`确定要冻结用户 ${username} 吗？\n冻结后该用户将无法登录。`)) {
        return;
    }

    try {
        const response = await fetch(`/api/admin/users/${userId}/freeze`, {
            method: 'POST',
            credentials: 'include'
        });

        const result = await response.json();

        if (result.success) {
            alert('✅ 用户已冻结');
            loadUsers();
        } else {
            throw new Error(result.error || '冻结失败');
        }
    } catch (error) {
        console.error('❌ 冻结用户失败:', error);
        alert('冻结失败: ' + error.message);
    }
}




async function unfreezeUser(userId, username) {
    if (!confirm(`确定要解冻用户 ${username} 吗？`)) {
        return;
    }

    try {
        const response = await fetch(`/api/admin/users/${userId}/unfreeze`, {
            method: 'POST',
            credentials: 'include'
        });

        const result = await response.json();

        if (result.success) {
            alert('✅ 用户已解冻');
            loadUsers();
        } else {
            throw new Error(result.error || '解冻失败');
        }
    } catch (error) {
        console.error('❌ 解冻用户失败:', error);
        alert('解冻失败: ' + error.message);
    }
}




async function deleteUser(userId, username) {
    if (!confirm(`⚠️ 警告！确定要删除用户 ${username} 吗？\n\n此操作将：\n- 删除该用户账号\n- 删除该用户的所有单词本\n- 删除该用户的翻译历史\n\n此操作不可恢复！`)) {
        return;
    }


    if (!confirm(`最后确认：真的要删除用户 ${username} 吗？`)) {
        return;
    }

    try {
        const response = await fetch(`/api/admin/users/${userId}`, {
            method: 'DELETE',
            credentials: 'include'
        });

        const result = await response.json();

        if (result.success) {
            alert('✅ 用户已删除');
            loadUsers();
        } else {
            throw new Error(result.error || '删除失败');
        }
    } catch (error) {
        console.error('❌ 删除用户失败:', error);
        alert('删除失败: ' + error.message);
    }
}




async function handleLogout() {
    if (!confirm('确定要登出吗？')) {
        return;
    }

    try {
        const response = await fetch('/api/auth/logout', {
            method: 'POST',
            credentials: 'include'
        });

        const result = await response.json();

        if (result.success) {
            window.location.href = '/login';
        }
    } catch (error) {
        console.error('登出错误:', error);
        window.location.href = '/login';
    }
}




function formatDate(isoString) {
    const date = new Date(isoString);
    return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
    });
}




function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}


window.openTokenModal = openTokenModal;
window.closeTokenModal = closeTokenModal;
window.resetTokens = resetTokens;
window.freezeUser = freezeUser;
window.unfreezeUser = unfreezeUser;
window.deleteUser = deleteUser;
window.handleLogout = handleLogout;

